package com.boge.core.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/fileDownLoad")
public class FileDownLoadController {
	
	@RequestMapping
	public void fileDownLoad(HttpServletRequest request, HttpServletResponse response) {
//		File file = new File(this.getClass().getResource("/").getPath());
//		String path = file.getAbsolutePath().replace("\\", "/");
//		String downLoadFileName = path + "/web.xml";
//		System.out.println("downLoadFileName:" + downLoadFileName);
		
//		String path = Thread.currentThread().getContextClassLoader().getResource("").toString();
//		String downLoadFileName = path.replace("\\", "/").replace("file:", "").replace("classes\\", "").substring(1) + "server.xml";
//		System.out.println("downLoadFileName:" + downLoadFileName);
		
		String projectPath = System.getProperty("user.dir");
		String downLoadFileName = projectPath.replace("\\", "/") + "/loggers/out.log";
		System.out.println("downLoadFileName:" + downLoadFileName);
		
		InputStream inputStream = null;
		OutputStream outputStream = null;
		
		try {
//			downLoadFileName = URLEncoder.encode(downLoadFileName, "UTF-8");
			inputStream = new FileInputStream(downLoadFileName);
			outputStream = response.getOutputStream();
			//指定文件下载而不是打开
//			response.setContentType( "application/x-msdownload");
			//1.设置文件ContentType类型，这样设置，会自动判断下载文件类型 
            response.setContentType("multipart/form-data");
			//设置下载文件名
			response.setHeader("Content-Disposition", "attachment;fileName=" + "out.log");
			byte[] bytes = new byte[1024];
			int len;
			while ((len = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes);
			}
			
		} catch (IOException e) {
			// TODO: handle exception
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}
			} catch (IOException e2) {
				// TODO: handle exception
			}
		}
		
	}

}
